package edu.manju.mimi.core.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <h4>mimi-core</h4>
 * <p>Token的签发与校验</p>
 *
 * @author : Lebei(lebei163@163.com)
 * @date : 2023-02-24 20:34
 **/
@Service
public class JwtService {
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;
    private static final String SECRET = "44aba4d0-bd41-4c05-8bd4-a3e4ee01fbcd"; // https://www.uuidgenerator.net/

    private final Algorithm algorithm;
    private final JWTVerifier verifier;

    public JwtService() {
        this.algorithm = Algorithm.HMAC256(SECRET);
        this.verifier = JWT.require(algorithm).build();
    }

    /**
     * 签发token
     *
     * @return 加密的token
     */
    public String sign(Integer id) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        return JWT.create()
                .withClaim("id", id)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 校验token是否正确
     *
     * @param token 密钥
     * @return 是否正确
     */
    public boolean verify(String token) {
        try {
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息，无需secret解密也能获得
     *
     * @return token中包含的id
     */
    public Long getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("id").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 判断过期
     *
     * @param token
     * @return
     */
    public boolean isExpire(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return System.currentTimeMillis() > jwt.getExpiresAt().getTime();
    }

    private static final String AUTH_HEADER_KEY = "X-Mimi-Auth";
    private static final String TOKEN_PREFIX = "Bearer ";

    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(AUTH_HEADER_KEY);
        if (token == null) return null;

        return token.replace(TOKEN_PREFIX, "");
    }
}
